<template>
  <div class="login-wrap">
    <transition
      name="fade"
    >
      <div  v-if="showlogin" class="ms-login">
        <div class="ms-title" style="color: #97a8be">项目追踪与管理系统</div>
        <el-form :model="param" :rules="rules2" ref="loginForm" label-width="0px" class="ms-content">
          <el-form-item prop="userId">
            <el-input v-model="param.userId" placeholder="请输入学号">
              <el-button slot="prepend" type="primary" icon="el-icon-user" size="small"></el-button>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              type="password"
              placeholder="请输入密码"
              v-model="param.password"
              @keyup.enter.native="submitForm('loginForm')"
            >
              <el-button slot="prepend" icon="el-icon-lock" size="small"></el-button>
            </el-input>
          </el-form-item>
          <div class="login-btn">
            <el-button type="primary" @click="submitForm('loginForm')">登录</el-button>
            <el-button type="primary" icon="el-icon-lx-forwardfill" @click="toRegister">注册</el-button>
          </div>
          <div style="text-align: center" v-model="reSetPasswordForm">
            <el-link type="primary" @click="reSetPasswordDialog = true">忘记密码？</el-link>
          </div>

          <!--重置密码弹窗-->
          <el-dialog
            title="密码重置"
            :visible.sync="reSetPasswordDialog"
             width="30%" @close="settingDialogClear">
            <el-form :model="reSetPasswordForm" label-width="80px" ref="updatePasswordForm" label-position="left"
                     :rules="updatePasswordRules">
              <el-form-item label="手机号:"  prop="phone">
                <el-input v-model="reSetPasswordForm.phone" size="medium"></el-input>
              </el-form-item>
              <el-form-item label="新密码:" prop="newPassword">
                <el-input type="password" v-model="reSetPasswordForm.newPassword" size="medium"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="reSetPasswordDialog = false">取 消</el-button>
                <el-button type="primary" @click="reSetPassword()">确 定</el-button>
            </span>
          </el-dialog>


        </el-form>
      </div>
    </transition>
    <transition
      name="fade"
    >
      <div   v-if="showreg" class="ms-register">
        <div class="ms-title1" style="color: #97a8be">
          <i class="el-icon-back" @click="toLogin()"></i>
          加入我们
          <i></i>
        </div>
        <el-form
          :model="regForm"
          :rules="rules"
          ref="register"
          label-width="0px"
          class="ms-content"
        >
          <el-form-item prop="userId">
            <el-input
              v-model="regForm.userId"
              placeholder="请输入学号"
            >
              <el-button slot="prepend" icon="el-icon-lx-favor"></el-button>
            </el-input>
          </el-form-item>
          <el-form-item prop="userName">
            <el-input
              v-model="regForm.userName"
              placeholder="请输入姓名"
            >
              <el-button slot="prepend" icon="el-icon-lx-people"></el-button>
            </el-input>
          </el-form-item>
          <el-form-item prop="phone">
            <el-input
              type="age"
              v-model="regForm.phone"
              placeholder="请输入手机号"
            >
              <el-button slot="prepend" icon="el-icon-lx-mobilefill"></el-button>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              type="password"
              placeholder="请输入密码"
              v-model="regForm.password"
            >
              <el-button slot="prepend" icon="el-icon-lx-lock"></el-button>
            </el-input>
          </el-form-item>
          <el-form-item prop="againPaswd">
            <el-input
              type="password"
              placeholder="请再次确认密码"
              v-model="regForm.againPaswd"
            >
              <el-button slot="prepend" icon="el-icon-lx-lock"></el-button>
            </el-input>
          </el-form-item>
          <el-form-item prop="account">
            <el-input
              placeholder="请输入码云账号(非必填)"
              v-model="regForm.account"
            >
              <el-button slot="prepend" icon="el-icon-lx-emoji"></el-button>
            </el-input>
          </el-form-item>
          <div class="login-btn">
            <el-button type="success" icon="el-icon-thumb" @click="registerForm">注册</el-button>
          </div>
        </el-form>
      </div>
    </transition>

  </div>
</template>

<script>
  export default {
    data: function() {
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.regForm.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      }
      var validatePhone = (rule, value, callback) => {
        if(!Number(value)){
          callback(new Error('请输入正确的手机号!'));
        }else{
          callback();
        }
      }
      return {
        showlogin: false,
        showreg: false,
        reSetPasswordDialog: false, //重置密码弹窗隐藏或显示
        param: {
          flag:'login',
          userId: '',
          password: ''
        },
        reSetPasswordForm: {
          phone: '',
          newPassword: ''
        },
        regForm:{
          userName: '',
          userId: '',
          password: '',
          againPaswd: '',
          phone: '',
          account: '',
        },
        rules2:{
          userId: [
            { required: true, message: '请输入学号', trigger: 'blur' },
          ],
          userName: [
            { required: true, message: '请输入姓名', trigger: 'blur' },
          ],
        },
        rules: {
          userId: [
            { required: true, message: '请输入学号', trigger: 'blur' },
            { min: 13 , message: '请输入13位的学号', trigger: 'blur' }
          ],
          userName: [
            { required: true, message: '请输入姓名', trigger: 'blur' },
          ],
          phone: [
            { required: true, message: '请输入手机'},
            { min: 11 , message: '请输入11位的手机'},
            { validator: validatePhone}
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' }
          ],
          againPaswd: [
            {validator: validatePass, trigger: 'blur' }
          ],
        },
        updatePasswordRules: {
           phone: [
             { required: true, message: '请输入手机'},
             { min: 11 , message: '请输入11位的手机'},
             { validator: validatePhone}
           ],
          newPassword: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 5,message: '密码不能小于5位', trigger: 'blur' }
          ]
        }
      };

    },
    mounted(){
      this.showlogin = true;
      console.log('mounted');

    },
    methods: {
      toRegister(){
        console.log(this.$refs.loginbox);
        this.showlogin=false;
        this.showreg=true;
      },
      toLogin(){
        this.showlogin=true;
        this.showreg=false;
      },
      registerForm(){
        this.$refs.register.validate(async valid => {
          if (valid) {
            var fd = new FormData();
            fd.append("userId",this.regForm.userId);
            fd.append("userName",this.regForm.userName);
            fd.append("paswd",this.regForm.password);
            fd.append("phone",this.regForm.phone);
            fd.append("code",this.regForm.account);
            console.log(fd)
            //发送axios请求
            const {data: res} = await this.$http.post('user/reg',fd);
            console.log(res);
            if (res.status == 200){
              this.$message.success(res.msg);
              //路由到登录页
              this.showreg = false;
              this.showlogin = true;
              return true;
            }else {
              return this.$message.error(res.msg);
            }
          }else{
            return  this.$message.error('请完整填写表单');
          }
        })

      },
      //用户登录
      submitForm(loginForm) {
        this.$refs[loginForm].validate(async valid => {
          if (valid) {
            var fd = new FormData();
            fd.append("userId",this.param.userId);
            fd.append("paswd",this.param.password);
            //发送ajax异步请求
            const {data: res} = await this.$http.post("/user/login",fd);
            if (res.status == 200){
              this.$message.success("登录成功！");
              //1、将登陆成功之后的token,保存到客户端的sessionStorage中
              //  1.1、项目中登录之外的API接口，必须在登录之后才能访问
              //  1.2、token只能在当前网站打开期间生效，所以保存在sessionStorage中
              window.sessionStorage.setItem("token",res.token);
              //当用户登录时，缓存登录用户的数据信息
              window.sessionStorage.setItem("user",JSON.stringify(res.data));
              //管理员
              if (res.data.userAuthority == 2){
                this.$router.push("/main");
              }else {
                //普通成员
                this.$router.push("/user/home");
              }
            }else {
              console.log(res);
              console.log(res.msg)
              this.$message.error(res.msg)
            }

          } else {
            this.$message.error('请输入账号和密码');
            console.log('error submit!!');
            return false;
          }
        });
      },
      //密码重置
      reSetPassword(){
        this.$refs.updatePasswordForm.validate(async valid => {
          if (valid){
            //发送put请求
            const {data: res} = await this.$http.put(`user/updatePassword/${this.reSetPasswordForm.phone}/${this.reSetPasswordForm.newPassword}`);
            console.log(res);
            if (res.status == 200){
              this.reSetPasswordDialog = false;
              return this.$message.success(res.msg);
            }else {
              return this.$message.error(res.msg);
            }
          }else {
            return this.$message.error("请填写完整表单");
          }
        });
      },
      settingDialogClear(){
        //重置表单数据
        this.$refs.updatePasswordForm.resetFields();
      }
    },
  };
</script>

<style scoped>
  .login-wrap {
    position: relative;
    width: 100%;
    height: 100%;
    /* background-color: #fff; */
    background-image: url('../../assets/img/login-bg.jpg');
    /* background-repeat: no-repeats; */
    background-size: 100%;

  }
  .imgTitle{
    display: flex;
    justify-content: center;
  }
  .ms-title {
    width: 100%;
    line-height: 50px;
    text-align: center;
    font-size: 20px;
    color: #fff;
    border-bottom: 1px solid #ddd;
  }
  .ms-title1 {
    display: flex;
    align-items: center;
    justify-content: space-between;
    line-height: 50px;
    text-align: center;
    font-size: 20px;
    color: #fff;
    border-bottom: 1px solid #ddd;
  }
  .ms-title1 i:nth-child(2){
    visibility:hidden
  }
  .ms-login {
    position: absolute;
    left: 50%;
    top: 50%;
    width: 350px;
    margin: -190px 0 0 -175px;
    border-radius: 5px;
    background: rgba(255, 255, 255, 0.3);
    overflow: hidden;
  }
  .back{
    float: left;
    margin-top: 13px;
    color: #fff;
  }
  .ms-register{
    position: absolute;
    left: 50%;
    top: 50%;
    width: 350px;
    margin: -270px 0 0 -175px;
    border-radius: 5px;
    background: rgba(255, 255, 255, 0.3);
    overflow: hidden;
    transform: translateY(10px);
  }
  .ms-content {
    padding: 30px 30px;
  }
  .login-btn {
    text-align: center;
    display: flex;
  }
  .login-btn button {
    width: 100%;
    height: 36px;
    margin-bottom: 10px;
  }
  .login-tips {
    font-size: 12px;
    line-height: 30px;
    color: #fff;
  }
  .fade-enter-active, .fade-leave-active {
    /* transition: opacity 1.5s; */
    transition: all 1.5s ease;
  }
  .fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
    opacity: 0;
    transform: translateY(50px);

  }
</style>
